/*
 * @Author: 0x9DEFA478
 * @Date: 2021-09-30 20:14:32
 * @LastEditTime: 2021-10-11 20:48:16
 * @LastEditors: 0x9DEFA478
 * @Description: 
 * QQ:2652450237
 * ============================================================================================================================================
 * 
 * 
 * 
 *                                                                                               ************      ****************************
 *                                                                                             ************      ****************************  
 *                                                                                           ************      ****************************    
 *                                                                                         ************      ****************************      
 *                                                                                       ************      ************                        
 *                                                                                     ************      ************                          
 *                                                                                   ************      ************                            
 *                                                                                 ************      ************                              
 *                                                                               ************      ************                                
 *                                                                             ************      ************                                  
 *                                                                           ************      ************                                    
 *                                                                         ************      ************                                      
 *                                                                       ************      ************                                        
 *                                                                     ************      ************                                          
 *                                                                   ************      ************                                            
 *                                                                 ************      ************                                              
 *                                                               ************      ************                                                
 *                                                             ************      ************                                                  
 *                                                           ************      ************                                                    
 *                                                         ************      ************                                                      
 *                                                       ************      ************                                                        
 *                                                     ************      ************                                                          
 *                                                   ************      ************                                                            
 *                                                 ************      ************                                                              
 *                                               ************      ************                                                                
 *                                             ************      ************                                                                  
 *                                           ************      ************                                                                    
 *                                         ************      ************                                                                      
 *                                       ************      ************                                                                        
 *                                     ************      ************                                                                          
 *                                   ************      ************                                                                            
 *                                 ************      ************                                                                              
 *                               ************      ************                                                                                
 *                             ************      ************                                                                                  
 *                           ************      ************                                                                                    
 *                         ************      ************                                                                                      
 *       ****************************      ************                                                                                        
 *     ****************************      ************                                                                                          
 *   ****************************      ************                                                                                            
 * ****************************      ************                                                                                              
 * 
 * 
 * 
 * ============================================================================================================================================
 * 
 */
#include "I_NFC.h"
#include "Peripherals_Instence.h"
#include "IP_GPIO.h"
#include "H_ThreadScheduler.h"
#include "MemoryMalloc.h"
#include "I_VCOM.h"
#include "H_String.h"




MFRC522* NFC1;
IC_Mifare1* Mifare1_1;
static H_TS_Semaphore* NFC1_SpiDoneSemaphore;
static H_TS_MessageQueue* CmdArray;


#define NFC1_SPI_CS_0()      oIP_GPIO_SetOutput_Low(GPIOB,12)
#define NFC1_SPI_CS_1()      oIP_GPIO_SetOutput_High(GPIOB,12)

#define NFC1_SPI_RES_0()     oIP_GPIO_SetOutput_Low(GPIOA,9)
#define NFC1_SPI_RES_1()     oIP_GPIO_SetOutput_High(GPIOA,9)



static void NFC_SendDoneCallback(void* v){
  while(IP_SPI_isBusy(ip_spi2)){
  }
  H_TS_SemaphoreGive_ISR(NFC1_SpiDoneSemaphore);
}

//============================================================================================================================================
//
// 底层回调
//
//============================================================================================================================================

static void Reset(){

  NFC1_SPI_CS_1();
  
  NFC1_SPI_RES_1();
	H_TS_ThreadSleep(2);
	NFC1_SPI_RES_0();
	H_TS_ThreadSleep(2);
	NFC1_SPI_RES_1();
  H_TS_ThreadSleep(2);

}


static void SendArray(void* tx,void* rx,int len,int speed){
  H_TS_Locking(ip_spi2_Lock);//锁定互斥锁

  if(speed==0){
    IP_SPI_SetSckFreq(ip_spi2,2);
  }else{
    IP_SPI_SetSckFreq(ip_spi2,7);
  }

  IP_SPI_SetTransDoneITCallback(ip_spi2,NFC_SendDoneCallback,NULL);
  
  NFC1_SPI_CS_0();

  if(len>0){
    IP_SPI_DMATxRx_IT_bytes(ip_spi2,tx,rx,len);
    H_TS_SemaphoreTake(NFC1_SpiDoneSemaphore);
  }

  NFC1_SPI_CS_1();

  H_TS_UnLock(ip_spi2_Lock);//释放互斥锁

}

//============================================================================================================================================
//
// 协议层回调
//
//============================================================================================================================================

//必须实现部分

//复位底层
static int Protocol_Reset(void* v){

  MFRC522_Reset(v);

  return vIC_Mifare1_Result_Ok;
}

//发送数据 (底层句柄,发送数据,发送位长度,最大等待时间)
int Protocol_Transmit(void* v,Hbyte* TxData,Hbyte TxBitLength,int WaitTime){
  int Result;

  Result=MFRC522_Transmit(v,TxData,TxBitLength,WaitTime);

  switch(Result){
    case vMFRC522_Result_Ok:
      return vIC_Mifare1_Result_Ok;
    case vMFRC522_Result_NoCard:
      return vIC_Mifare1_Result_NoCard;
    default:
      break;
  }

  return vIC_Mifare1_Result_Error;
}

//接收数据 (底层句柄,接收数据,最大接收位长度,接收位长度,最大等待时间)
int Protocol_Receive(void* v,Hbyte* RxData,Hbyte MaxRxBitLengthPtr,Hbyte* RxBitLengthPtr,int WaitTime){
  int Result;

  Result=MFRC522_Receive(v,RxData,MaxRxBitLengthPtr,RxBitLengthPtr,WaitTime);

  switch(Result){
    case vMFRC522_Result_Ok:
      return vIC_Mifare1_Result_Ok;
    case vMFRC522_Result_NoCard:
      return vIC_Mifare1_Result_NoCard;
    default:
      break;
  }

  return vIC_Mifare1_Result_Error;
}

//发送接收数据 (底层句柄,发送数据,发送位长度,接收数据,最大接收位长度,接收位长度,最大等待时间)
int Protocol_Transceive(void* v,Hbyte* TxData,Hbyte TxBitLength,Hbyte* RxData,Hbyte MaxRxBitLengthPtr,Hbyte* RxBitLengthPtr,int WaitTime){
  int Result;

  Result=MFRC522_Transceive(v,TxData,TxBitLength, RxData,MaxRxBitLengthPtr,RxBitLengthPtr,WaitTime);

  switch(Result){
    case vMFRC522_Result_Ok:
      return vIC_Mifare1_Result_Ok;
    case vMFRC522_Result_NoCard:
      return vIC_Mifare1_Result_NoCard;
    default:
      break;
  }

  return vIC_Mifare1_Result_Error;
}

//三轮认证 密钥认证 (底层句柄,卡ID,块地址,密钥)
int Protocol_MFAuthent(void* v,Hbyte* SerialNumber,Hbyte BlockAddr,int AuthentType,Hbyte* Password){
  int Result;

  switch(AuthentType){
    case vIC_Mifare1_AuthentType_A:
      AuthentType=vMFRC522_MFAuthent_AuthentType_A;
      break;
    case vIC_Mifare1_AuthentType_B:
      AuthentType=vMFRC522_MFAuthent_AuthentType_B;
      break;
    default:
      return vIC_Mifare1_Result_Error;
  }

  Result=MFRC522_MFAuthent(v,SerialNumber,BlockAddr,AuthentType,Password);

  if(Result==vMFRC522_Result_Ok){
    return vIC_Mifare1_Result_Ok;
  }

  return vIC_Mifare1_Result_Error;
}
  

//可选实现部分 (如果不需要 固定返回vIC_Mifare1_Result_Ok)

//在卡检测之前被调用
int Protocol_CallBeforeProbeCard(void* v){
  return vIC_Mifare1_Result_Ok;
}

//在卡操作完成之后被调用
int Protocol_CallAfterHaltCard(void* v){
  MFRC522_ClearMFCrypto1On(v);
  return vIC_Mifare1_Result_Ok;
}

//底层有效性检查 返回vIC_Mifare1_Result_Ok表明底层硬件有效 否则底层硬件无效
int Protocol_BspIsValid(void* v){

  if(vMFRC522_Result_Ok!=MFRC522_IsExist(v)){
    return vIC_Mifare1_Result_Error;
  }

  return vIC_Mifare1_Result_Ok;
}



//============================================================================================================================================
//
// 用户回调
//
//============================================================================================================================================

static unsigned char TempBuf[512];
static unsigned char DefaultPassword[]={0xFF,0xFF,0xFF,0xFF,0xFF,0xFF};
static unsigned char PasswordA[]={0x00,0x00,0x78,0xA4,0xEF,0x9D};
static unsigned char PasswordB[]={0x00,0x00,0x00,'C','Y','H'};

static struct{
  int dValue;
}Communication_Status;





static void CommunicationCallback_DeInit(IC_Mifare1* _this,IC_Mifare1_CommunicationCallback_Param* Param){
  unsigned char BlockData[16];
  unsigned char PasswordBlockData[16];
  unsigned char* strBuf;
  char* str;
  int Result;
  unsigned char Sector;
  unsigned char Block;
  int i;

  int AuthentIsOk;

  strBuf=TempBuf;

  if(Param->SerialNumberLength==4){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]);
  }else if(Param->SerialNumberLength==7){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]
    ,(unsigned int)Param->SerialNumber[4]
    ,(unsigned int)Param->SerialNumber[5]
    ,(unsigned int)Param->SerialNumber[6]);
  }else if(Param->SerialNumberLength==10){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]
    ,(unsigned int)Param->SerialNumber[4]
    ,(unsigned int)Param->SerialNumber[5]
    ,(unsigned int)Param->SerialNumber[6]
    ,(unsigned int)Param->SerialNumber[7]
    ,(unsigned int)Param->SerialNumber[8]
    ,(unsigned int)Param->SerialNumber[9]);
  }else{
    str=H_String(strBuf,"\r\n识别到错误卡\r\n序列号长度:{i}\r\n",Param->SerialNumberLength);
  }
  I_VCOM_In(strBuf,H_StringGetLength(str));
  str=H_String(strBuf,"ATQA:{X4}\r\n",Param->ATQA);
  I_VCOM_In(strBuf,H_StringGetLength(str));

  str="\r\n  开始对块6进行操作";
  I_VCOM_In(str,H_StringGetLength(str));

  Result=IC_Mifare1_Authent(_this,7,vIC_Mifare1_AuthentType_A,PasswordA);
  if(Result==vIC_Mifare1_Result_Ok){

    str="\r\n    密码A验证成功";
    I_VCOM_In(str,H_StringGetLength(str));

    Result=IC_Mifare1_Authent(_this,7,vIC_Mifare1_AuthentType_B,PasswordB);
    if(Result==vIC_Mifare1_Result_Ok){
      str="\r\n    密码B验证成功";
      I_VCOM_In(str,H_StringGetLength(str));
      AuthentIsOk=-1;
    }else{
      str="\r\n    密码B验证失败";
      I_VCOM_In(str,H_StringGetLength(str));
      AuthentIsOk=0;
    }

  }else{
    str="\r\n  密码A验证失败";
    I_VCOM_In(str,H_StringGetLength(str));
    AuthentIsOk=0;
  }

  if(AuthentIsOk!=0){
    str="\r\n  密钥验证成功";
    I_VCOM_In(str,H_StringGetLength(str));

    for(i=0;i<6;i++){
      PasswordBlockData[i]=DefaultPassword[i];
      PasswordBlockData[10+i]=DefaultPassword[i];
    }
    PasswordBlockData[6]=0xFFU;
    PasswordBlockData[7]=0x07U;
    PasswordBlockData[8]=0x80U;
    PasswordBlockData[9]=0x69U;

    Result=IC_Mifare1_WriteBlock(_this,7,PasswordBlockData);
    if(Result==vIC_Mifare1_Result_Ok){
      str="\r\n    默认密钥写入成功";
      I_VCOM_In(str,H_StringGetLength(str));
    }else{
      str="\r\n    默认密钥写入失败";
      I_VCOM_In(str,H_StringGetLength(str));
    }
    

  }else{
    str="\r\n  密钥验证失败";
    I_VCOM_In(str,H_StringGetLength(str));
  }

  if(Result==vIC_Mifare1_Result_Ok){
    str="\r\n  操作成功";
    I_VCOM_In(str,H_StringGetLength(str));
  }

  str="\r\n  卡操作结束\r\n";
  I_VCOM_In(str,H_StringGetLength(str));

  
}

static void CommunicationCallback_Init(IC_Mifare1* _this,IC_Mifare1_CommunicationCallback_Param* Param){
  unsigned char BlockData[16];
  unsigned char PasswordBlockData[16];
  unsigned char* strBuf;
  char* str;
  int Result;
  unsigned char Sector;
  unsigned char Block;
  int i;

  int AuthentIsOk;

  strBuf=TempBuf;

  if(Param->SerialNumberLength==4){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]);
  }else if(Param->SerialNumberLength==7){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]
    ,(unsigned int)Param->SerialNumber[4]
    ,(unsigned int)Param->SerialNumber[5]
    ,(unsigned int)Param->SerialNumber[6]);
  }else if(Param->SerialNumberLength==10){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]
    ,(unsigned int)Param->SerialNumber[4]
    ,(unsigned int)Param->SerialNumber[5]
    ,(unsigned int)Param->SerialNumber[6]
    ,(unsigned int)Param->SerialNumber[7]
    ,(unsigned int)Param->SerialNumber[8]
    ,(unsigned int)Param->SerialNumber[9]);
  }else{
    str=H_String(strBuf,"\r\n识别到错误卡\r\n序列号长度:{i}\r\n",Param->SerialNumberLength);
  }
  I_VCOM_In(strBuf,H_StringGetLength(str));
  str=H_String(strBuf,"ATQA:{X4}\r\n",Param->ATQA);
  I_VCOM_In(strBuf,H_StringGetLength(str));

  str="\r\n  开始对块6进行操作";
  I_VCOM_In(str,H_StringGetLength(str));

  Result=IC_Mifare1_Authent(_this,7,vIC_Mifare1_AuthentType_A,DefaultPassword);
  if(Result==vIC_Mifare1_Result_Ok){

    str="\r\n    默认密码A验证成功";
    I_VCOM_In(str,H_StringGetLength(str));

    Result=IC_Mifare1_Authent(_this,7,vIC_Mifare1_AuthentType_B,DefaultPassword);
    if(Result==vIC_Mifare1_Result_Ok){
      str="\r\n    默认密码B验证成功";
      I_VCOM_In(str,H_StringGetLength(str));
      AuthentIsOk=-1;
    }else{
      str="\r\n    默认密码B验证失败";
      I_VCOM_In(str,H_StringGetLength(str));
      AuthentIsOk=0;
    }

  }else{
    str="\r\n  默认密码A验证失败";
    I_VCOM_In(str,H_StringGetLength(str));
    AuthentIsOk=0;
  }

  if(AuthentIsOk!=0){
    str="\r\n  密钥验证成功";
    I_VCOM_In(str,H_StringGetLength(str));

    Result=IC_Mifare1_ReadBlock(_this,7,PasswordBlockData);
    if(Result==vIC_Mifare1_Result_Ok){
      str=H_String(strBuf,"\r\n    控制字读取成功: {X2}{X2}{X2}",(int)PasswordBlockData[6],(int)PasswordBlockData[7],(int)PasswordBlockData[8]);
      I_VCOM_In(str,H_StringGetLength(str));

      if((PasswordBlockData[6]!=0xFFU)||(PasswordBlockData[7]!=0x07U)||(PasswordBlockData[8]!=0x80U)){
        str="\r\n      不合法的控制字";
        I_VCOM_In(str,H_StringGetLength(str));
        Result=vIC_Mifare1_Result_Error;
      }

    }else{
      str="\r\n    控制字读取失败";
      I_VCOM_In(str,H_StringGetLength(str));
    }

    if(Result==vIC_Mifare1_Result_Ok){
      IC_Mifare1_MakeValueBlock(BlockData,6,100*100);
      Result=IC_Mifare1_WriteBlock(_this,6,BlockData);
      if(Result==vIC_Mifare1_Result_Ok){
        str="\r\n    初始化数值写入成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    初始化数值写入失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

    if(Result==vIC_Mifare1_Result_Ok){
      Result=IC_Mifare1_WriteBlock(_this,5,BlockData);
      if(Result==vIC_Mifare1_Result_Ok){
        str="\r\n    备份初始化数值写入成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    备份初始化数值写入失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

    if(Result==vIC_Mifare1_Result_Ok){
      H_StringCopy(BlockData,"By 0x9DEFA478");
      Result=IC_Mifare1_WriteBlock(_this,4,BlockData);
      if(Result==vIC_Mifare1_Result_Ok){
        str="\r\n    标记写入成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    标记写入失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

    if(Result==vIC_Mifare1_Result_Ok){

      for(i=0;i<6;i++){
        PasswordBlockData[i]=PasswordA[i];
        PasswordBlockData[10+i]=PasswordB[i];
      }

      Result=IC_Mifare1_WriteBlock(_this,7,PasswordBlockData);
      if(Result==vIC_Mifare1_Result_Ok){
        str="\r\n    新密钥写入成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    新密钥写入失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

  }else{
    str="\r\n  密钥验证失败";
    I_VCOM_In(str,H_StringGetLength(str));
  }

  if(Result==vIC_Mifare1_Result_Ok){
    str="\r\n  操作成功";
    I_VCOM_In(str,H_StringGetLength(str));
  }

  str="\r\n  卡操作结束\r\n";
  I_VCOM_In(str,H_StringGetLength(str));

  
}

static void CommunicationCallback_Read(IC_Mifare1* _this,IC_Mifare1_CommunicationCallback_Param* Param){
  unsigned char BlockData[16];
  unsigned char BlockData_Back[16];
  unsigned char* strBuf;
  char* str;
  int Result;
  unsigned char ValRes;
  unsigned char ValRes_Back;
  unsigned char Block;
  unsigned char Block_Back;
  unsigned int blockValue;
  unsigned int blockValue_Back;
  int i;

  int AuthentIsOk;

  strBuf=TempBuf;

  if(Param->SerialNumberLength==4){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]);
  }else if(Param->SerialNumberLength==7){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]
    ,(unsigned int)Param->SerialNumber[4]
    ,(unsigned int)Param->SerialNumber[5]
    ,(unsigned int)Param->SerialNumber[6]);
  }else if(Param->SerialNumberLength==10){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]
    ,(unsigned int)Param->SerialNumber[4]
    ,(unsigned int)Param->SerialNumber[5]
    ,(unsigned int)Param->SerialNumber[6]
    ,(unsigned int)Param->SerialNumber[7]
    ,(unsigned int)Param->SerialNumber[8]
    ,(unsigned int)Param->SerialNumber[9]);
  }else{
    str=H_String(strBuf,"\r\n识别到错误卡\r\n序列号长度:{i}\r\n",Param->SerialNumberLength);
  }
  I_VCOM_In(strBuf,H_StringGetLength(str));
  str=H_String(strBuf,"ATQA:{X4}\r\n",Param->ATQA);
  I_VCOM_In(strBuf,H_StringGetLength(str));


  str="\r\n  开始对块6进行操作";
  I_VCOM_In(str,H_StringGetLength(str));

  Result=IC_Mifare1_Authent(_this,7,vIC_Mifare1_AuthentType_A,PasswordA);
  if(Result==vIC_Mifare1_Result_Ok){

    str="\r\n    密码A验证成功";
    I_VCOM_In(str,H_StringGetLength(str));

    Result=IC_Mifare1_Authent(_this,7,vIC_Mifare1_AuthentType_B,PasswordB);
    if(Result==vIC_Mifare1_Result_Ok){
      str="\r\n    密码B验证成功";
      I_VCOM_In(str,H_StringGetLength(str));
      AuthentIsOk=-1;
    }else{
      str="\r\n    密码B验证失败";
      I_VCOM_In(str,H_StringGetLength(str));
      AuthentIsOk=0;
    }

  }else{
    str="\r\n  密码A验证失败";
    I_VCOM_In(str,H_StringGetLength(str));
    AuthentIsOk=0;
  }



  if(AuthentIsOk!=0){
    str="\r\n  密钥验证成功";
    I_VCOM_In(str,H_StringGetLength(str));

    Result=IC_Mifare1_ReadBlock(_this,4,BlockData);
    if(Result==vIC_Mifare1_Result_Ok){
      str="\r\n    用户数据读取成功:\r\n      ";
      I_VCOM_In(str,H_StringGetLength(str));

      BlockData[15]='\0';
      str=BlockData;
      I_VCOM_In(str,H_StringGetLength(str));
    }else{
      str="\r\n    用户数据读取失败";
      I_VCOM_In(str,H_StringGetLength(str));
    }

    if(Result==vIC_Mifare1_Result_Ok){
      Result=IC_Mifare1_ReadBlock(_this,6,BlockData);

      if(Result==vIC_Mifare1_Result_Ok){
        str="\r\n    读取成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    读取失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

    if(Result==vIC_Mifare1_Result_Ok){
      Result=IC_Mifare1_ReadBlock(_this,5,BlockData_Back);

      if(Result==vIC_Mifare1_Result_Ok){
        str="\r\n    备份块读取成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    备份块读取失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

    if(Result==vIC_Mifare1_Result_Ok){

      ValRes=IC_Mifare1_ValueBlockGetValue(BlockData,&Block,&blockValue);
      ValRes_Back=IC_Mifare1_ValueBlockGetValue(BlockData_Back,&Block_Back,&blockValue_Back);

      if(((ValRes&vIC_Mifare1_ValueBlockGetValue_Value_Msk)==vIC_Mifare1_ValueBlockGetValue_Value_Error)
        &&((ValRes_Back&vIC_Mifare1_ValueBlockGetValue_Value_Msk)==vIC_Mifare1_ValueBlockGetValue_Value_Error)){
        
        str="\r\n    所有数据均错误 无法恢复";
        I_VCOM_In(str,H_StringGetLength(str));

        Result=vIC_Mifare1_Result_Error;
      }else if(((ValRes&vIC_Mifare1_ValueBlockGetValue_Value_Msk)==vIC_Mifare1_ValueBlockGetValue_Value_Ok)
        &&((ValRes_Back&vIC_Mifare1_ValueBlockGetValue_Value_Msk)==vIC_Mifare1_ValueBlockGetValue_Value_Ok)){
        //数据均完整

        if((ValRes&vIC_Mifare1_ValueBlockGetValue_Addr_Msk)!=vIC_Mifare1_ValueBlockGetValue_Addr_Ok){
          IC_Mifare1_MakeValueBlock(BlockData,6,blockValue);
          Result=IC_Mifare1_WriteBlock(_this,6,BlockData);

          if(Result==vIC_Mifare1_Result_Ok){
            str="\r\n    部分地址错误 修复完毕";
            I_VCOM_In(str,H_StringGetLength(str));
          }else{
            str="\r\n    部分地址错误 修复失败";
            I_VCOM_In(str,H_StringGetLength(str));
          }
        }

        if((ValRes_Back&vIC_Mifare1_ValueBlockGetValue_Addr_Msk)!=vIC_Mifare1_ValueBlockGetValue_Addr_Ok){
          //BlockData中的数据已经完整
          Result=IC_Mifare1_WriteBlock(_this,5,BlockData);
          if(Result==vIC_Mifare1_Result_Ok){
            str="\r\n    备份部分地址错误 修复完毕";
            I_VCOM_In(str,H_StringGetLength(str));
          }else{
            str="\r\n    备份部分地址错误 修复失败";
            I_VCOM_In(str,H_StringGetLength(str));
          }
        }
      }else{
        //有数据能识别

        if((ValRes&vIC_Mifare1_ValueBlockGetValue_Value_Msk)!=vIC_Mifare1_ValueBlockGetValue_Value_Error){
          //如果原块数据完整 则以此数据为准

          IC_Mifare1_MakeValueBlock(BlockData_Back,6,blockValue);
          Result=IC_Mifare1_WriteBlock(_this,5,BlockData_Back);

          if(Result==vIC_Mifare1_Result_Ok){
            str="\r\n    备份部分数据错误 修复完毕";
            I_VCOM_In(str,H_StringGetLength(str));
          }else{
            str="\r\n    备份部分数据错误 修复失败";
            I_VCOM_In(str,H_StringGetLength(str));
          }
        }else{
          //以备份块为准

          IC_Mifare1_MakeValueBlock(BlockData,6,blockValue_Back);
          Result=IC_Mifare1_WriteBlock(_this,6,BlockData);

          if(Result==vIC_Mifare1_Result_Ok){
            str="\r\n    部分数据错误 修复完毕";
            I_VCOM_In(str,H_StringGetLength(str));
          }else{
            str="\r\n    部分数据错误 修复失败";
            I_VCOM_In(str,H_StringGetLength(str));
          }
        }
      }

    }
    
  }else{
    str="\r\n  密钥验证失败";
    I_VCOM_In(str,H_StringGetLength(str));
  }

  if(Result==vIC_Mifare1_Result_Ok){
    Result=IC_Mifare1_ReadBlock(_this,6,BlockData);

    if(Result==vIC_Mifare1_Result_Ok){
      str="\r\n    读取成功";
      I_VCOM_In(str,H_StringGetLength(str));

      ValRes=IC_Mifare1_ValueBlockGetValue(BlockData,&Block,&blockValue);

      if(ValRes==0){

        str=H_String(strBuf,"\r\n    读取到->当前值: {i}, 块地址: {i}",blockValue,(int)Block);
        I_VCOM_In(strBuf,H_StringGetLength(str));
      }else{
        str="\r\n    读取的数据错误, 可能为修复失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }

    }else{
      str="\r\n    读取失败";
      I_VCOM_In(str,H_StringGetLength(str));
    }
  }



  str="\r\n卡操作结束\r\n";
  I_VCOM_In(str,H_StringGetLength(str));

  
}

static void CommunicationCallback_Decrement(IC_Mifare1* _this,IC_Mifare1_CommunicationCallback_Param* Param){
  unsigned char BlockData[16];
  unsigned char BlockData_Back[16];
  unsigned char* strBuf;
  char* str;
  int Result;
  unsigned char ValRes;
  unsigned char ValRes_Back;
  unsigned char Block;
  unsigned char Block_Back;
  unsigned int blockValue;
  unsigned int blockValue_Back;
  int i;

  int IsDecrement;
  Huint32 dValue;

  int AuthentIsOk;

  strBuf=TempBuf;

  if(Param->SerialNumberLength==4){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]);
  }else if(Param->SerialNumberLength==7){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]
    ,(unsigned int)Param->SerialNumber[4]
    ,(unsigned int)Param->SerialNumber[5]
    ,(unsigned int)Param->SerialNumber[6]);
  }else if(Param->SerialNumberLength==10){
    str=H_String(strBuf,"\r\n识别到卡\r\n序列号长度:{i}\r\nSAK:0x{X2}\r\n序列号:{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}{X2}\r\n",Param->SerialNumberLength,(unsigned int)Param->SAK
    ,(unsigned int)Param->SerialNumber[0]
    ,(unsigned int)Param->SerialNumber[1]
    ,(unsigned int)Param->SerialNumber[2]
    ,(unsigned int)Param->SerialNumber[3]
    ,(unsigned int)Param->SerialNumber[4]
    ,(unsigned int)Param->SerialNumber[5]
    ,(unsigned int)Param->SerialNumber[6]
    ,(unsigned int)Param->SerialNumber[7]
    ,(unsigned int)Param->SerialNumber[8]
    ,(unsigned int)Param->SerialNumber[9]);
  }else{
    str=H_String(strBuf,"\r\n识别到错误卡\r\n序列号长度:{i}\r\n",Param->SerialNumberLength);
  }
  I_VCOM_In(strBuf,H_StringGetLength(str));
  str=H_String(strBuf,"ATQA:{X4}\r\n",Param->ATQA);
  I_VCOM_In(strBuf,H_StringGetLength(str));


  str="\r\n  开始对块6进行操作";
  I_VCOM_In(str,H_StringGetLength(str));

  Result=IC_Mifare1_Authent(_this,7,vIC_Mifare1_AuthentType_A,PasswordA);
  if(Result==vIC_Mifare1_Result_Ok){

    str="\r\n    密码A验证成功";
    I_VCOM_In(str,H_StringGetLength(str));

    Result=IC_Mifare1_Authent(_this,7,vIC_Mifare1_AuthentType_B,PasswordB);
    if(Result==vIC_Mifare1_Result_Ok){
      str="\r\n    密码B验证成功";
      I_VCOM_In(str,H_StringGetLength(str));
      AuthentIsOk=-1;
    }else{
      str="\r\n    密码B验证失败";
      I_VCOM_In(str,H_StringGetLength(str));
      AuthentIsOk=0;
    }

  }else{
    str="\r\n  密码A验证失败";
    I_VCOM_In(str,H_StringGetLength(str));
    AuthentIsOk=0;
  }



  if(AuthentIsOk!=0){
    str="\r\n  密钥验证成功";
    I_VCOM_In(str,H_StringGetLength(str));

    Result=IC_Mifare1_ReadBlock(_this,4,BlockData);
    if(Result==vIC_Mifare1_Result_Ok){
      str="\r\n    用户数据读取成功:\r\n      ";
      I_VCOM_In(str,H_StringGetLength(str));

      BlockData[15]='\0';
      str=BlockData;
      I_VCOM_In(str,H_StringGetLength(str));
    }else{
      str="\r\n    用户数据读取失败";
      I_VCOM_In(str,H_StringGetLength(str));
    }

    if(Result==vIC_Mifare1_Result_Ok){
      Result=IC_Mifare1_ReadBlock(_this,6,BlockData);

      if(Result==vIC_Mifare1_Result_Ok){
        str="\r\n    读取成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    读取失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

    if(Result==vIC_Mifare1_Result_Ok){
      Result=IC_Mifare1_ReadBlock(_this,5,BlockData_Back);

      if(Result==vIC_Mifare1_Result_Ok){
        str="\r\n    备份块读取成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    备份块读取失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

    if(Result==vIC_Mifare1_Result_Ok){

      ValRes=IC_Mifare1_ValueBlockGetValue(BlockData,&Block,&blockValue);
      ValRes_Back=IC_Mifare1_ValueBlockGetValue(BlockData_Back,&Block_Back,&blockValue_Back);

      if(((ValRes&vIC_Mifare1_ValueBlockGetValue_Value_Msk)==vIC_Mifare1_ValueBlockGetValue_Value_Error)
        &&((ValRes_Back&vIC_Mifare1_ValueBlockGetValue_Value_Msk)==vIC_Mifare1_ValueBlockGetValue_Value_Error)){
        
        str="\r\n    所有数据均错误 无法恢复";
        I_VCOM_In(str,H_StringGetLength(str));

        Result=vIC_Mifare1_Result_Error;
      }else if(((ValRes&vIC_Mifare1_ValueBlockGetValue_Value_Msk)==vIC_Mifare1_ValueBlockGetValue_Value_Ok)
        &&((ValRes_Back&vIC_Mifare1_ValueBlockGetValue_Value_Msk)==vIC_Mifare1_ValueBlockGetValue_Value_Ok)){
        //数据均完整

        if((ValRes&vIC_Mifare1_ValueBlockGetValue_Addr_Msk)!=vIC_Mifare1_ValueBlockGetValue_Addr_Ok){
          IC_Mifare1_MakeValueBlock(BlockData,6,blockValue);
          Result=IC_Mifare1_WriteBlock(_this,6,BlockData);

          if(Result==vIC_Mifare1_Result_Ok){
            str="\r\n    部分地址错误 修复完毕";
            I_VCOM_In(str,H_StringGetLength(str));
          }else{
            str="\r\n    部分地址错误 修复失败";
            I_VCOM_In(str,H_StringGetLength(str));
          }
        }

        if((ValRes_Back&vIC_Mifare1_ValueBlockGetValue_Addr_Msk)!=vIC_Mifare1_ValueBlockGetValue_Addr_Ok){
          //BlockData中的数据已经完整
          Result=IC_Mifare1_WriteBlock(_this,5,BlockData);
          if(Result==vIC_Mifare1_Result_Ok){
            str="\r\n    备份部分地址错误 修复完毕";
            I_VCOM_In(str,H_StringGetLength(str));
          }else{
            str="\r\n    备份部分地址错误 修复失败";
            I_VCOM_In(str,H_StringGetLength(str));
          }
        }
      }else{
        //有数据能识别

        if((ValRes&vIC_Mifare1_ValueBlockGetValue_Value_Msk)!=vIC_Mifare1_ValueBlockGetValue_Value_Error){
          //如果原块数据完整 则以此数据为准

          IC_Mifare1_MakeValueBlock(BlockData_Back,6,blockValue);
          Result=IC_Mifare1_WriteBlock(_this,5,BlockData_Back);

          if(Result==vIC_Mifare1_Result_Ok){
            str="\r\n    备份部分数据错误 修复完毕";
            I_VCOM_In(str,H_StringGetLength(str));
          }else{
            str="\r\n    备份部分数据错误 修复失败";
            I_VCOM_In(str,H_StringGetLength(str));
          }
        }else{
          //以备份块为准

          IC_Mifare1_MakeValueBlock(BlockData,6,blockValue_Back);
          Result=IC_Mifare1_WriteBlock(_this,6,BlockData);

          if(Result==vIC_Mifare1_Result_Ok){
            str="\r\n    部分数据错误 修复完毕";
            I_VCOM_In(str,H_StringGetLength(str));
          }else{
            str="\r\n    部分数据错误 修复失败";
            I_VCOM_In(str,H_StringGetLength(str));
          }
        }
      }

    }
    
  }else{
    str="\r\n  密钥验证失败";
    I_VCOM_In(str,H_StringGetLength(str));
  }


  if(Result==vIC_Mifare1_Result_Ok){


    if(Communication_Status.dValue>0){
      IsDecrement=0;
      dValue=Communication_Status.dValue;
    }else if(Communication_Status.dValue<0){
      IsDecrement=-1;
      dValue=-Communication_Status.dValue;
    }else{
      Result=vIC_Mifare1_Result_Error;
      str="\r\n    值加减失败";
      I_VCOM_In(str,H_StringGetLength(str));
    }

    if(Result==vIC_Mifare1_Result_Ok){
      Result=IC_Mifare1_ValueOperation(_this,6,IsDecrement,dValue);
      if(Result!=vIC_Mifare1_Result_Ok){
        str="\r\n    值加减失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    值加减成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

    if(Result==vIC_Mifare1_Result_Ok){
      Result=IC_Mifare1_ValueTransfer(_this,6);
      if(Result!=vIC_Mifare1_Result_Ok){
        str="\r\n    值保存失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        Communication_Status.dValue=0;
        str="\r\n--->值保存成功<---";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }


    if(Result==vIC_Mifare1_Result_Ok){

      str="\r\n  数值已修改";
      I_VCOM_In(str,H_StringGetLength(str));

      Result=IC_Mifare1_ReadBlock(_this,6,BlockData);

      if(Result==vIC_Mifare1_Result_Ok){
        str="\r\n    读取成功";
        I_VCOM_In(str,H_StringGetLength(str));

        ValRes=IC_Mifare1_ValueBlockGetValue(BlockData,&Block,&blockValue);

        if(ValRes==0){

          str=H_String(strBuf,"\r\n    读取到->当前值: {i}, 块地址: {i}",blockValue,(int)Block);
          I_VCOM_In(strBuf,H_StringGetLength(str));

        }else{
          str="\r\n    读取的数据错误, 可能为修复失败";
          I_VCOM_In(str,H_StringGetLength(str));
        }

      }else{
        str="\r\n    读取失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }
    }

    if(Result==vIC_Mifare1_Result_Ok){
      Result=IC_Mifare1_ValueOperation(_this,5,IsDecrement,dValue);
      if(Result!=vIC_Mifare1_Result_Ok){
        str="\r\n    备份值加减失败";
        I_VCOM_In(str,H_StringGetLength(str));
      }else{
        str="\r\n    备份值加减成功";
        I_VCOM_In(str,H_StringGetLength(str));
      }
      

      if(Result==vIC_Mifare1_Result_Ok){
        Result=IC_Mifare1_ValueTransfer(_this,5);
        if(Result!=vIC_Mifare1_Result_Ok){
          str="\r\n    备份值保存失败";
          I_VCOM_In(str,H_StringGetLength(str));
        }else{
          str="\r\n    备份值保存成功";
          I_VCOM_In(str,H_StringGetLength(str));
        }
      }
    }
  }


  str="\r\n卡操作结束\r\n";
  I_VCOM_In(str,H_StringGetLength(str));

  
}



H_TS_Thread* I_NFC_ThreadHandle;
static int I_NFC_Thread(void* v){
  void* v0;
  void* v1;
  unsigned char strBuf[32];
  void (*CommunicationCallback)(IC_Mifare1*,IC_Mifare1_CommunicationCallback_Param*);

  CommunicationCallback=NULL;

  for(;;){
    if(0==H_TS_MessageQueueReceive_Time(CmdArray,&v0,&v1,1)){
      if(cH_IsNull(v0)&&cH_IsNull(v1)){
        H_String(strBuf,"Version:0x{X2}\r\n",(unsigned int)NFC1->Version);

        I_VCOM_In(strBuf,H_StringGetLength((char*)strBuf));
      }else{

        CommunicationCallback=v1;
      }
    }

    if(CommunicationCallback==CommunicationCallback_DeInit){
      IC_Mifare1_Communication(Mifare1_1,CommunicationCallback_DeInit,0);
    }else if(CommunicationCallback==CommunicationCallback_Init){
      IC_Mifare1_Communication(Mifare1_1,CommunicationCallback_Init,0);
    }else if(CommunicationCallback==CommunicationCallback_Read){
      IC_Mifare1_Communication(Mifare1_1,CommunicationCallback_Read,0);
    }else if(CommunicationCallback==CommunicationCallback_Decrement){
      Communication_Status.dValue=((int*)v0)[0];
      if(Communication_Status.dValue!=0){
        IC_Mifare1_Communication(Mifare1_1,CommunicationCallback_Decrement,0);
      }
      while(Communication_Status.dValue!=0){
        H_TS_ThreadSleep(1);
        IC_Mifare1_Communication(Mifare1_1,CommunicationCallback_Decrement,0);
      }
      CommunicationCallback=CommunicationCallback_Read;
    }else{
    }
    
  }
}

/**
 * @brief 发送队列指令
 * @param v0 指令参数
 * @param v1 指令参数
 * @return 0:成功 其他:失败
 */
int I_NFC_SnedCMD(void* v0,void* v1){
  return H_TS_MessageQueueSend(CmdArray,v0,v1);
}

/**
 * @brief 发送指令
 * @param Mode 模式
 * @param dValue 变化的值
 * @return 0:成功 其他:失败
 */
int I_NFC_SetMode(int Mode,int dValue){
  static int dvalue;

  dvalue=dValue;

  switch(Mode){
    case vI_NFC_Mode_DeInit:
      return I_NFC_SnedCMD(NULL,CommunicationCallback_DeInit);
    case vI_NFC_Mode_Init:
      return I_NFC_SnedCMD(NULL,CommunicationCallback_Init);
    case vI_NFC_Mode_Read:
      return I_NFC_SnedCMD(NULL,CommunicationCallback_Read);
    case vI_NFC_Mode_ValueChange:
      return I_NFC_SnedCMD(&dvalue,CommunicationCallback_Decrement);
    default:
      return -1;
  }
}

/**
 * @brief NFC初始化
 * @return 无
 */
void I_NFC_Init(){
  unsigned char* TxSequenceBuffer;
  unsigned char* RxSequenceBuffer;
  MFRC522_LL_Function LL_Function_Bsp;
  IC_Mifare1_LL_Function LL_Function_Protocol;

  //信号量 队列
  NFC1_SpiDoneSemaphore=new_H_TS_Semaphore(1);
  CmdArray=new_H_TS_MessageQueue(16);


  //NFC底层
  NFC1=MemoryMalloc_Malloc(sizeof(MFRC522));
  TxSequenceBuffer=MemoryMalloc_Malloc(vMFRC522_TxSequenceBufferLength);
  RxSequenceBuffer=MemoryMalloc_Malloc(vMFRC522_RxSequenceBufferLength);

  if(cH_IsNull(NFC1)||cH_IsNull(CmdArray)||cH_IsNull(TxSequenceBuffer)||cH_IsNull(RxSequenceBuffer)){
    for(;;){
    }
  }

  LL_Function_Bsp.Type=vMFRC522_LL_Function_Type_SPI;
  LL_Function_Bsp.Delay=H_TS_ThreadSleep;
  LL_Function_Bsp.Reset=Reset;
  LL_Function_Bsp.TransferSequence.Transfer_SPI=SendArray;
  MFRC522_Init(NFC1,&LL_Function_Bsp,TxSequenceBuffer,RxSequenceBuffer,vMFRC522_ProtocolType_ISO14443_A);

  //NFC协议层
  Mifare1_1=MemoryMalloc_Malloc(sizeof(IC_Mifare1));


  LL_Function_Protocol.v=NFC1;
  LL_Function_Protocol.Reset=Protocol_Reset;
  LL_Function_Protocol.Transmit=Protocol_Transmit;
  LL_Function_Protocol.Receive=Protocol_Receive;
  LL_Function_Protocol.Transceive=Protocol_Transceive;
  LL_Function_Protocol.MFAuthent=Protocol_MFAuthent;
  LL_Function_Protocol.CallBeforeProbeCard=Protocol_CallBeforeProbeCard;
  LL_Function_Protocol.CallAfterHaltCard=Protocol_CallAfterHaltCard;
  LL_Function_Protocol.BspIsValid=Protocol_BspIsValid;
  IC_Mifare1_Init(Mifare1_1,&LL_Function_Protocol);

  I_NFC_ThreadHandle=H_TS_StartNewThread(I_NFC_Thread,NULL,1024,16,0);
  if(cH_IsNull(I_NFC_ThreadHandle)){
    for(;;){
    }
  }
  I_NFC_ThreadHandle->ThreadName="I_NFC_Thread";
  

}


